import json
import re

from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from pymysql import DatabaseError
from redis import StrictRedis

from users.models import User


class RegisterView(View):
    def post(self, request):
        # 1. 接收参数  ajax请求,  接收的是 body中的  json数据
        data = json.loads(request.body.decode())

        username = data.get('username')
        password = data.get('password')
        password2 = data.get('password2')
        mobile = data.get('mobile')
        sms_code = data.get('sms_code')
        allow = data.get('allow')

        # 2. 校验参数
        # 判断参数是否齐全
        if not all([username, password, password2, mobile, sms_code, allow]):
            return JsonResponse({'code': '999', 'msg': '缺少必传参数'})
        # 判断用户名是否是5-20个字符
        if not re.match(r'^[a-zA-Z0-9_]{5,20}$', username):
            return JsonResponse({'code': '999', 'msg': '请输入5-20个字符的用户名'})
        # 判断密码是否是8-20个数字
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return JsonResponse({'code': '999', 'msg': '请输入8-20位的密码'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': '999', 'msg': '手机号码格式不正确'})
        if not sms_code:
            return JsonResponse({'code': '999', 'msg': '没有验证码'})
        # 判断两次密码是否一致
        if password != password2:
            return JsonResponse({'code': '999', 'msg': '两次输入的密码不一致'})
        # 判断是否勾选用户协议
        if not allow:
            return JsonResponse({'code': '999', 'msg': '请勾选用户协议'})
        # 判断手机验证码
        client = StrictRedis()
        redis_sms_code = client.get(mobile)
        if redis_sms_code:
            redis_sms_code = redis_sms_code.decode()
        else:
            redis_sms_code = None
        if sms_code == redis_sms_code:
            pass
        else:
            return JsonResponse({'code': '999', 'msg': '短信验证码错误'})

        # 3. 生成用户
        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except Exception as e:
            return JsonResponse({'code': '999', 'msg': '注册失败'})
        # 4. 返回响应
        return JsonResponse({'code': '0', 'msg': 'ok', 'username': user.username, 'id': user.id, 'token': '000'})


class LoginView(View):
    def post(self, request):
        # 1. 接收参数
        data = json.loads(request.body.decode())

        username = data.get('username')
        password = data.get('password')
        # 2. 校验数据
        # 判断参数是否齐全
        if not all([username, password]):
            return JsonResponse({'code': '999', 'msg': '缺少必传参数'})
        # 判断用户名是否是5-20个字符
        if not re.match(r'^[a-zA-Z0-9_]{8,20}$', username):
            return JsonResponse({'code': '999', 'msg': '请输入8-20个字符的用户名'})
        # 判断密码是否是8-20个数字
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return JsonResponse({'code': '999', 'msg': '请输入8-20位的密码'})
        # 3. 认证用户
        try:
            user = User.objects.get(username=username)
        except Exception as e:
            return JsonResponse({'code': '999', 'msg': '用户不存在'})

        if user.check_password(password):
            return JsonResponse({'code': '0', 'msg': '登录成功',
                                 'username': user.username,
                                 'id': user.id,
                                 'token': '000'})
        else:
            return JsonResponse({'code': '999', 'msg': '密码错误'})
        # 4. 返回用户信息


class UsernameCountView(View):
    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        return JsonResponse({'code': '0', 'msg': 'ok', 'count': count})


class MobileCountView(View):
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        return JsonResponse({'code': '0', 'msg': 'ok', 'count': count})
